<?php
/**
 * Created by PhpStorm.
 * User: chen
 * Date: 18-5-26
 * Time: 下午8:00
 */

namespace App\ServiceHandler\Common;

use App\Model\Common\Authority;
use App\Model\Common\Module;
use Illuminate\Support\Facades\DB;

class AuthorityService
{
    /**
     * 修改和添加方法，修改时传入id
     * @param $array
     * @param null $id
     * @return bool|null
     */
    public static function post($array, $id = null){
        $module = null;
        if(empty($id)){
            $module = new Authority();
        }else{
            $module = Authority::find($id);
        }
        $module->name = $array['name'];
        $module->type = $array['type'];
        $module->module_id = $array['module_id'];
        if($module->isValid()){
            return $module->save();
        }
        return $module->errors;
    }

    /**
     * 查询所有权限
     * @return mixed
     */
    public static function lists(){
        return Authority::paginate(Authority::per_page());
    }

    /**
     * 根据模块ID 查询该模块下的所有权限
     */
    public static function getListsForMid($id, $pageLimit)
    {
        $list = DB::table('nosplit_authority')
            ->where('module_id', $id)
            ->select('id', 'name', 'type', 'created_at', 'updated_at')
            ->orderBy('id', 'desc')
            ->paginate($pageLimit);
        if (sizeof($list) == 0) {
            return false;
        }
        return $list;
    }

    /**
     * 查询所有模块的权限
     * @return array
     */
    public static function listsAllOfModule(){
        $module = Module::all();
        foreach ($module as $item){
            $item->authorities;
        }
        return $module->toArray();
    }


}